package com.gitee.zzh.demo.controller;

import com.gitee.zzh.common.base.BaseResponse;
import com.gitee.zzh.common.jwt.JwtToken;
import com.gitee.zzh.demo.service.ImgCheckCodeService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
public class ImageCodeController {

    @Resource
    private ImgCheckCodeService imgCheckCodeService;

    //http://localhost:8080/createCode
    @RequestMapping(value = "/createCode", method = {RequestMethod.GET})
    public BaseResponse<Object> createCode(){
        BaseResponse<Object> baseResponse = new BaseResponse<>();
        String codes = imgCheckCodeService.codeCreate();
        String token = JwtToken.createToken(codes, 120);
        baseResponse.ok(token);
        return baseResponse;
    }

    //http://localhost:8080/imgCode?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjaGVja0NvZGUiOiJUMjdzIiwiZXhwIjoxNzU5Mjg3Mjg2LCJpYXQiOjE3NTkyODcxNjZ9.KTwy-i_eauD_DUIyUlfq83qFWFZdYpJ5fvrfJ5LJRZg
    @RequestMapping(value = "/imgCode", method = {RequestMethod.GET})
    public void imgCode(HttpServletResponse resp, @RequestParam String token){
        resp.setHeader("Pragma", "No-cache");
        resp.setHeader("Cache-Control", "No-cache");
        resp.setDateHeader("Expires", 0);
        try {
            String checkCode = JwtToken.getCheckCode(token);
            imgCheckCodeService.imageWrite(resp.getOutputStream(), checkCode);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //http://localhost:8080/checkCode?checkCode=t9eg&token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjaGVja0NvZGUiOiJUOWVnIiwiZXhwIjoxNzU3NDMxNTIzLCJpYXQiOjE3NTc0MzE0MDN9.UZmvO0rHnEMKGOkLH13Ok0BsAAYWCWS6RVT3pDFZ0qc
    @RequestMapping(value = "/checkCode", method = {RequestMethod.GET})
    public BaseResponse<?> checkCode(@RequestParam String checkCode, @RequestParam String token){
        BaseResponse<?> baseResponse = new BaseResponse<>();
        String checkCode1 = JwtToken.getCheckCode(token);
        if("".equals(checkCode1)) {
            baseResponse.errMsg("验证码已过期");
            return baseResponse;
        }
        if(checkCode1.equalsIgnoreCase(checkCode)){
            baseResponse.ok();
        } else {
            baseResponse.errMsg("验证码不正确");
        }
        return baseResponse;
    }
}
